var Manager;
var json_resp;
//SETTING UP OUR POPUP  
//0 means disabled; 1 means enabled;  
var popupStatus = 0;  



//loading popup with jQuery magic!  
function loadPopup(){  
//loads popup only if it is disabled  
if(popupStatus==0){  
$("#backgroundPopup").css({  
"opacity": "0.7"  
});  
$("#backgroundPopup").fadeIn("slow");  
$("#popupContact").fadeIn("slow");  
popupStatus = 1;  
}  
}  

//disabling popup with jQuery magic!  
function disablePopup(){  
//disables popup only if it is enabled  
if(popupStatus==1){  
$("#backgroundPopup").fadeOut("slow");  
$("#popupContact").fadeOut("slow");  
popupStatus = 0;  
}  
}  


//centering popup  
function centerPopup(){  
//request data for centering  
var windowWidth = 1300; //document.documentElement.clientWidth;  
var windowHeight = 700; //document.documentElement.clientHeight;  
var popupHeight = $("#popupContact").height();  
var popupWidth = $("#popupContact").width();  
//centering  
$("#popupContact").css({  
"position": "absolute",  
//"top": windowHeight/2-popupHeight/2,  
//"left": windowWidth/2-popupWidth/2  
"top" : 50,
"left" : 100
});  
//only need force for IE6  
  
$("#backgroundPopup").css({  
"height": windowHeight  
});  
  
}    

function getShortTitle(title)
{
	return title.substring(0,10) + ' ...';
}
function mycarousel_getItemHTML(item)
{
    return '<div class="bestSellerItemContainer"><div class="itemBox" style="border: 1px solid #808080; width: 150px; height: 150px; background-image: none; background-position: center center; background-repeat: no-repeat;"><a href="#" onClick="getBookDetails(\'ISBN:' + item.ISBN + '\'); return false;"><img src="' + item.turl + '" width="150" height="150" alt="' + item.turl + '" /></a></div><div class="bestSellerCarouselTxt" title="' + item.title + '">'+ getShortTitle(item.title) + '</div><div class="bestSellerCarouselPrice">'+ item.sprice + '</div>';    
}

function getItemHTML(item)
{
    return '<div class="thmbbx"><div class="thumbContainer"><div class="itemBox" style="border: 1px solid #808080; width: 150px; height: 150px; background-image: none; background-position: center center; background-repeat: no-repeat;"><a href="#" onClick="getBookDetails(\'ISBN:' + item.ISBN + '\'); return false;"><img src="' + item.turl + '" width="150" height="150" alt="' + item.turl + '" /></a></div><div class="bestSellerCarouselTxt" title="' + item.title + '">'+ getShortTitle(item.title) +'</div><div class="bestSellerCarouselPrice">'+ item.sprice + '</div></div>';    
}

function getItemDetailsHTML(item)
{
	
	
	
	var sHTML = '<div style="clear:both; padding-top:20px; width:100%;">';
		sHTML += '<div style="float:left; height:360px; width:40%;">';               
		sHTML += '<div style="clear:both">';
		sHTML += '<img  id= "imagePosition"  src="' + item.iurl+ '" width="275" ; height:"275"></img></td>';
		sHTML += '</div>';
		sHTML += '<div style="clear:both"></div>';   				
		sHTML += '</div>';
		sHTML += '<div align="left" style="padding-left:20px; float:right; width:50%;">';
		sHTML += '<div style="clear:both; width:100%;">';
		sHTML += '<div style="float:left">';
		sHTML += '<h3 id="booktitle">' + item.title + '</h3>';
		sHTML += '</div>';						
		sHTML += '</div>';
		sHTML += '<div style="clear:both; width:100%; padding-bottom:15px;">';
		sHTML += '<h4 id="bookmedium">' + item.medium + '</h4>';
		sHTML += '</div>';
		if (item.medium == 'Audio' || item.medium == 'Video')
		{
			sHTML += '<div id="button" style="clear:both; width:100%; padding-top:15px; padding-bottom:15px;">';
			sHTML += '<a href="#" onClick="onPreview(); return false;">Preview</a>';
			sHTML += '</div>';
		}		
		sHTML += '<div id="bookauthors" style="clear:both; width:100%;">' + item.authorfn + ' ' + item.authorln + '(Author)';                   
		sHTML += '</div>';
		sHTML += '<div style="clear:both; width:100%; padding-top:15px;">';                	
		sHTML += '<div class="priceblock" align="right" style="float:left">List Price:</div>';
		sHTML += '<div id="idlistprice" class="listprice" align="left" style="float:left; padding-left:5px;">' + item.rprice + '</div>';                   
		sHTML += '</div>';
		sHTML += '<div style="clear:both; width:100%; padding-top:15px;">';                	
		sHTML += '<div class="priceblock" align="right" style="float:left">SalePrice:</div>';
		sHTML += '<div id="idsaleprice" class="saleprice" align="left" style="float:left; padding-left:5px;">' + item.sprice + '</div>';                   
		sHTML += '</div>';
		sHTML += '<div style="clear:both; width:100%; padding-top:15px;">';     
		if (item.instock)
		{
			sHTML += '<div id="idinstock" class="availGreen" align="right" style="float:left">In Stock,</div>';
			sHTML += '<div id="idqty" class="availGreen" align="left" style="float:left; padding-left:5px;">' + item.qty + '</div>';  
			sHTML += '<div id="idavailtext" class="availGreen" align="left" style="float:left; padding-left:5px;">Available</div>'; 
		}
		else
		{
			sHTML += '<div id="idoos" class="notavailRed" align="right" style="float:left;">Out of Stock</div>';                
		}	
		sHTML += '</div>';
		sHTML += '<div style="clear:both; width:100%; padding-top:15px;">';                	
		sHTML += '<div class="priceblock" align="right" style="float:left">Edition:</div>';
		sHTML += '<div id="idbookedition" class="bookdata" align="left" style="float:left; padding-left:5px;">' + item.edition + '</div>';                   
		sHTML += '</div>';
		sHTML += '<div style="clear:both; width:100%; padding-top:10px;">';                	
		sHTML += '<div class="priceblock" align="right" style="float:left">Publication Date:</div>';
		sHTML += '<div id="idpubdate" class="bookdata" align="left" style="float:left; padding-left:5px;">' + item.pubyear + '</div>';                   
		sHTML += '</div>';    
		sHTML += '<div style="clear:both; width:100%; padding-top:10px;">';                	
		sHTML += '<div class="priceblock" align="right" style="float:left">Publisher:</div>';
		sHTML += '<div id="idpub" class="bookdata" align="left" style="float:left; padding-left:5px;">' + item.pubname + '</div>';                   
		sHTML += '</div>';   
		sHTML += '<div style="clear:both; width:100%; padding-top:10px;">';                	
		sHTML += '<div class="priceblock" align="right" style="float:left">ISBN-10:</div>';
		sHTML += '<div id="idisbn" class="bookdata" align="left" style="float:left; padding-left:5px;">' + item.ISBN + '</div>';                   
		sHTML += '</div>';                                                
		sHTML += '</div>';            
		sHTML += '</div>';
		sHTML += '<div style="clear:both; padding-top:1px; width:100%;">';
		sHTML += '<div style="float:left; width:40%;">';		
		sHTML += '</div>';
		sHTML += '<div align="left" style="padding-left:20px; float:right; width:50%;">Location:<br>' + item.street + '<br>';
		sHTML += item.city + ' ' + item.state + ' ' + item.zipcode;
		sHTML += '<div id="map_canvas" style="width:350px; height: 350px; margin-left: auto; margin-right: auto"></div>';                             
		sHTML += '</div>';            
		sHTML += '</div>';   
		
		if (item.medium == 'Audio' || item.medium == 'Video')
		{
			if (item.medium == 'Video')
			{
				sHTML += '<div id="popupContact" style="height:550;width:600;">';
			}
			else
			{
				sHTML += '<div id="popupContact" style="height:150;width:400;">';	
			}
			sHTML += '<a id="popupContactClose" onClick="disablePopup(); return false;">close</a>';  
			sHTML += '<h1>Like it? Shop Now!</h1>'; 
			if (item.medium == 'Audio')
			{
				sHTML += '<audio controls preload="auto" autobuffer>';  				
				sHTML += '<source src="http://www.kevinroseworld.com/Music/OkaVanga/OkaVanga/BajeLaCalle.ogg"/>';
				sHTML += 'Your browser does not support the audio element.';
				sHTML += '</audio>';
			}
			else
			{
				sHTML += '<video controls preload="auto" autobuffer width="480" height="360">'
				sHTML += '<source src="http://www.808.dk/pics/video/gizmo.ogv" type="video/ogg" />';
				sHTML += 'Your browser does not support the audio element.';
				sHTML += '</video>';	
			}
				        
			sHTML += '<p id="contactArea">';  	               
			sHTML += 'Press ESCAPE, Click on close (right-top) or Click Out from the popup to close the popup!';  	                	            
			sHTML += '</p>';  
			sHTML += '</div>';  
			sHTML += '<div id="backgroundPopup" onClick="disablePopup(); return false;"></div>';
		}
		
		return sHTML;
}

function mycarousel_itemLoadCallback(carousel, state)
{
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }
        if (i > json_resp.response.docs.length) {
            break;
        }
        carousel.add(i, mycarousel_getItemHTML(json_resp.response.docs[i-1]));
    }
}

function splitString(field, value, condition) 
{
	  var subqstr="";
	  var token = value.split(" ");
	  for (i=0; i< token.length; i++){
	    subqstr += escape(field) + ':*' + escape(token[i]) + '*' ;	
		if (i != token.length-1)
		  subqstr += ' ' + condition + ' ';
	  }
	  return subqstr;
}

function showLocation(lat, lng) {
  	var latlng = new google.maps.LatLng(lat, lng);
	var myOptions = {zoom: 18, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	var marker = new google.maps.Marker({position: latlng, map: map, });
  }

function callsolr(strquery, resultwidget)
{
		Manager = new AjaxSolr.Manager({solrUrl: 'http://localhost:8080/solr/'});
        Manager.addWidget(resultwidget);
        Manager.init();
        Manager.store.addByValue('q', strquery);
        Manager.store.addByValue('rows', 50);
        Manager.doRequest();
}

function calladvsolr(strquery, strsort, resultwidget)
{
		Manager = new AjaxSolr.Manager({solrUrl: 'http://localhost:8080/solr/'});
        Manager.addWidget(resultwidget);
        Manager.init();
        Manager.store.addByValue('q', strquery);
        Manager.store.addByValue('sort', strsort);
        Manager.store.addByValue('rows', 50);
        Manager.doRequest();
}

function gsearch(strquery)
{
	callsolr(strquery, new AjaxSolr.GResultWidget({id: 'g1result', target: '#dyncont'}))
}

function advsearch(strquery, strsort)
{
	calladvsolr(strquery, strsort, new AjaxSolr.GResultWidget({id: 'g2result', target: '#dyncont'}))
}

function header_search()
{
	//alert("Yay!");
	var sSearchQuery;
	var sSearchBy = $('#search-by').val();
	//alert(sSearchBy); return;
	var sSearchText = escape($.trim(($('#search-text').val()))); 
	if ( sSearchText != '')
	{
		if (sSearchBy == 4)
			sSearchQuery = splitString('ISBN', sSearchText, 'AND'); //'ISBN:' + escape(sSearchText); //splitString('ISBN', sSearchText, 'OR');
		else if (sSearchBy == 2)
			sSearchQuery = splitString('title', sSearchText, 'AND'); //'title:' + escape(sSearchText); //splitString('title', sSearchText, 'OR');
		else if (sSearchBy == 3)
			sSearchQuery = splitString('author', sSearchText, 'AND'); //'author:' + escape(sSearchText); //splitString('author', sSearchText, 'OR');
		else 
			sSearchQuery = splitString('all_text', sSearchText, 'AND'); //'all_text:' + escape(sSearchText); //splitString('all_text', sSearchText, 'OR');
		
		if (sSearchBy == 4)
			getBookDetails(sSearchQuery);
		else
			gsearch(sSearchQuery);
	}
}

function getSortOpts()
{
	var sSortQuery = '';
	var sortBy = $('#search-sort-by').val();
	if (sortBy != 1)
	{
		if (sortBy == 2)
			sSortQuery = 'authorfn asc';
		else if (sortBy == 3)
			sSortQuery = 'title asc';
		else if (sortBy == 4)
			sSortQuery = 'sprice asc';
	}
	
	return sSortQuery;	
}

function advance_search()
{
	//alert("Yay!");
	var sSearchQuery = '';
	var sAllTextSearchQuery = '';
	var sSortOpts = '';
	var sSearchText1 = escape($.trim($('#adv-search1-text').val()));
	var sSearchText2 = escape($.trim($('#adv-search2-text').val()));
	var sSearchText3 = escape($.trim($('#adv-search3-text').val()));
	var sLastOpts;
		
	if ($('#category').val() == null && $('#price').val() == null && $('#format').val() == null && $('#language').val() == null && sSearchText1 == '' && sSearchText2 == '' && sSearchText1 == '')
		return;
	
	sLastOpts = '#adv-search1-opts';
	
	//alert('Gotcha!');
	if (sSearchText1 != '')
	{
		if ($('#adv-search1-by').val() == 4)		
			sSearchQuery += splitString('ISBN', sSearchText1, 'AND'); // 'ISBN:' + sSearchText1;
		else if ($('#adv-search1-by').val() == 2)
			sSearchQuery += splitString('author', sSearchText1, 'AND'); //'author:' + sSearchText1;
		else if ($('#adv-search1-by').val() == 3)
			sSearchQuery += splitString('title', sSearchText1, 'AND'); //'title:' + sSearchText1;
		else
			sAllTextSearchQuery += 'all_text:' + escape(sSearchText1);
			//sSearchQuery += splitString('author', sSearchText1, 'AND') + ' OR ' + splitString('title', sSearchText1, 'AND') + ' OR ' + splitString('ISBN', sSearchText1, 'AND');//'author:' + sSearchText1 + ' OR ' + 'title:' + sSearchText1 + ' OR ' + 'ISBN:' + sSearchText1;				
	}		
	
	if (sSearchText2 != '')
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		if ($('#adv-search2-by').val() == 4)		
			sSearchQuery += splitString('ISBN', sSearchText2, 'AND'); // 'ISBN:' + sSearchText2;
		else if ($('#adv-search2-by').val() == 2)
			sSearchQuery += splitString('author', sSearchText2, 'AND'); //'author:' + sSearchText2;
		else if ($('#adv-search2-by').val() == 3)
			sSearchQuery += splitString('title', sSearchText2, 'AND'); //'title:' + sSearchText2;
		else
		{
			if (sAllTextSearchQuery != '')
			{
				sAllTextSearchQuery += ' ' + $(sLastOpts).val() + ' ';
			}	
			sAllTextSearchQuery += 'all_text:' + escape(sSearchText2);
			//sSearchQuery += splitString('author', sSearchText2, 'AND') + ' OR ' + splitString('title', sSearchText2, 'AND') + ' OR ' + splitString('ISBN', sSearchText2, 'AND');//'author:' + sSearchText2 + ' OR ' + 'title:' + sSearchText2 + ' OR ' + 'ISBN:' + sSearchText2;
		}
		
		sLastOpts = '#adv-search2-opts';
	}
	
	
	if (sSearchText3 != '')
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		if ($('#adv-search3-by').val() == 4)		
			sSearchQuery += splitString('ISBN', sSearchText3, 'AND'); //'ISBN:' + sSearchText3;
		else if ($('#adv-search3-by').val() == 2)
			sSearchQuery += splitString('author', sSearchText3, 'AND'); //'author:' + sSearchText3;
		else if ($('#adv-search3-by').val() == 3)
			sSearchQuery += splitString('title', sSearchText3, 'AND'); //'title:' + sSearchText3;
		else
		{
			if (sAllTextSearchQuery != '')
			{
				sAllTextSearchQuery += ' ' + $(sLastOpts).val() + ' ';
			}	
			sAllTextSearchQuery += 'all_text:' + escape(sSearchText3);
			//sSearchQuery += splitString('author', sSearchText3, 'AND') + ' OR ' + splitString('title', sSearchText3, 'AND') + ' OR ' + splitString('ISBN', sSearchText3, 'AND');//'author:' + sSearchText3 + ' OR ' + 'title:' + sSearchText3 + ' OR ' + 'ISBN:' + sSearchText3;		
		}
		sLastOpts = '#adv-search3-opts';
	}
	
	if ($('#category').val() != null)
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		sSearchQuery += 'sid:' + $('#category').val();
	}
	
	if ($('#price').val() != null)
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		if ($('#price').val() == 1)
			sSearchQuery += 'sprice:[* TO 10]';
		else if ($('#price').val() == 2)
			sSearchQuery += 'sprice:[10 TO 25]';
		else if ($('#price').val() == 3)
			sSearchQuery += 'sprice:[25 TO 50]';
		else 
			sSearchQuery += 'sprice:[50 TO *]';
	}
	
	if ($('#format').val() != null)
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		sSearchQuery += 'medium:' + $('#format').val();
	}
	
	if ($('#language').val() != null)
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		sSearchQuery += 'language:' + $('#language').val();
	}
		
	var chkInStock = document.getElementById('adv-chk-oos');
	if (chkInStock.checked)
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		sSearchQuery += 'instock:true';
	}
	
	if (sAllTextSearchQuery != '') 
	{
		if (sSearchQuery != '')
		{
			sSearchQuery += ' ' + $(sLastOpts).val() + ' ';
		}
		
		sSearchQuery += sAllTextSearchQuery;
	}
	
	//alert(sSearchQuery);
	
	sSortOpts = getSortOpts();
	//alert(sSortOpts);
	
	if (sSortOpts == '')
		gsearch(sSearchQuery);
	else
		advsearch(sSearchQuery, sSortOpts);
				
}

function getBookDetails(strquery)
{
	callsolr(strquery, new AjaxSolr.DResultWidget({id: 'dresult', target: '#dyncont'}))
}

function onPreview()
{	
	centerPopup();  	
	loadPopup();  
}

(function ($) {

AjaxSolr.HResultWidget = AjaxSolr.AbstractWidget.extend({  
    afterRequest: function () {   
		//alert("hi");
                 
            json_resp = this.manager.response;
            jQuery('#mycarousel').jcarousel({
                    size: json_resp.response.docs.length,
                    itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback}
                });

        }
});

AjaxSolr.GResultWidget = AjaxSolr.AbstractWidget.extend({  
    afterRequest: function () {   		
        
    	var strmsg;
		$(this.target).empty();
		$(this.target).addClass("galmin");
		$('#msgcont').empty();
		if (this.manager.response.response.docs.length == 1)
			strmsg = 'Your search returned "' + this.manager.response.response.docs.length + '" Book!';
		else
			strmsg = 'Your search returned "' + this.manager.response.response.docs.length + '" Books!';
		$('#msgcont').append(strmsg);
 		for (var i = 0; i <= this.manager.response.response.docs.length; i++) {        
        		var itemHTML = getItemHTML(this.manager.response.response.docs[i]); 
        		$(this.target).append(itemHTML);
    		}            

	}
});

AjaxSolr.DResultWidget = AjaxSolr.AbstractWidget.extend({  
    afterRequest: function () {   		
        
    	var strmsg;
		$(this.target).empty();
		$(this.target).addClass("galmin");
		$('#msgcont').empty();						
		
 		if (this.manager.response.response.docs.length > 0)
 		{
 			strmsg = 'Book Details!';
 			var item = this.manager.response.response.docs[0];
        	var itemHTML = getItemDetailsHTML(item); 
        	$(this.target).append(itemHTML);
        	
        	showLocation(item.latitude, item.longitude);        	
    	}            
 		else
 		{
 			strmsg = 'Ops! count not find the book, please try again!';
 		}
 		
 		$('#msgcont').append(strmsg);
	}
});

})(jQuery);

(function ($) {    
jQuery(document).ready(function() {    
 
	callsolr('sid:7', new AjaxSolr.HResultWidget({id: 'result'}))		
	
}); 
})(jQuery); 